/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import process from 'process';

import { boot } from '../../base/boot/index.js';
import { BuildEvent, WatchEvent } from '../../base/common/daemon-protocol/build-event.js';
import { DefaultDaemonConnector } from '../../base/daemon/connection/default-daemon-connector.js';
import { HvigorDaemonClientLogger } from '../../base/daemon/log/hvigor-daemon-client-log.js';
import { coreParameter } from '../../base/internal/data/global-core-parameters.js';
import { HvigorCliOptions } from '../../base/util/options/hvigor-cli-options.js';
import prettyHrtime from '../../common/util/pretty-hrtime.js';
import { handleBuildStatus, handleWatchBuildResult, handleWatchLog, printLog } from '../handler/client-event-handler.js';

const log = HvigorDaemonClientLogger.getLogger('daemon-client');

export async function daemonBoot(cliArgv: HvigorCliOptions) {
  const beginTime = process.hrtime();
  const daemonConnector = new DefaultDaemonConnector();
  const connection = await daemonConnector.getDaemonConnection();
  if (connection) {
    connection.on(BuildEvent.BUILD_STATUS, handleBuildStatus);
    connection.on(BuildEvent.OUTPUT, printLog);
    connection.on(WatchEvent.WATCH_RESULT, handleWatchBuildResult);
    connection.on(WatchEvent.WATCH_LOG, handleWatchLog);

    connection.emit(BuildEvent.COMMON_BUILD, cliArgv);
    log.debug(`hvigor client: Connection initTime: ${prettyHrtime(process.hrtime(beginTime))}`);
  } else {
    // 直接以冷启动的方式执行
    // 该分支no-daemon方式启动 修改初始参数的daemon为false 后续可以走no-daemon的分支清理进程
    coreParameter.startParams.daemon = false;
    log.warn('hvigor client: Failed to find or create an available daemon. Build will be executed in no-daemon mode.');
    await boot(cliArgv);
  }
  process.on('exit', (exitCode) => {
    log.debug('hvigor client: Connection will disconnect and exit process.');
    connection?.disconnect();
    process.exit(exitCode ?? 0);
  });
}
